package net.wanglu.www.zzz.main;

import java.util.ArrayList;
import java.util.Collection;

public class DataBufferPool {

	private boolean isEnd = false;
	private ArrayList<Object> pool = new ArrayList<Object>(2048);
	
	public synchronized boolean isEnd() {
		return isEnd;
	}
	public synchronized void setEnd(boolean isEnd) {
		this.isEnd = isEnd;
		notifyAll();
	}

	public synchronized boolean isEmptyPool() {
		return pool.size() == 0;
	}
	
	public void pourInto(Object data) throws Exception {
		// TODO Auto-generated method stub
		
		synchronized(this) {
			if ( data instanceof Collection<?>) {
				Collection<?> ldata = (Collection<?>) data;
				pool.addAll(ldata);
			} else {
				pool.add(data);
			}
			
			notifyAll();
		}
	}

	public Object pourOut() throws Exception {
		// TODO Auto-generated method stub
		ArrayList<Object> al = new ArrayList<Object>();
		synchronized(this) {
			while( pool.isEmpty() && !isEnd) {
				wait();
			}
			al.addAll(pool);
			pool.clear();
			notifyAll();
		}
		return al;
	}
	
	public synchronized void finishPool() {
		this.isEnd = true;
		pool.clear();
		notifyAll();
	}
}
